package com.kpmg.datalake.common.controller;

import com.kpmg.datalake.common.enums.ResultCodeEnum;
import com.kpmg.datalake.common.exception.BusinessException;
import com.kpmg.datalake.common.utils.ContextHolderUtils;
import com.kpmg.datalake.common.vo.ServerResponse;
import com.kpmg.datalake.common.vo.UserDTO;

import java.io.Serializable;

/**
 * @author Alex.zhao [alex.zhao@kpmg.com]
 * @since Created on azhao6 on 2018-06-27 13:18:04
 */
public class BaseController {
    /**
     * 获取当前用户
     *
     * @return UserDTO
     */
    public UserDTO getLoginUser() {
        return ContextHolderUtils.getLoginUser();
    }

    /**
     * 操作失败
     *
     * @param <T> 返回对象类型
     * @return Result
     */
    public <T extends Serializable> ServerResponse<T> doError() {
        return ServerResponse.createByError();
    }

    /**
     * 操作失败
     *
     * @param msg 错误信息
     * @param <T> 返回对象类型
     * @return Result
     */
    public <T extends Serializable> ServerResponse<T> doError(String msg) {
        return ServerResponse.createByErrorMessage(msg);
    }
    /**
     * 操作失败
     *
     * @param resultCodeEnum 错误信息
     * @param <T> 返回对象类型
     * @return Result
     */
    public <T extends Serializable> ServerResponse<T> doError(ResultCodeEnum resultCodeEnum) {
        return ServerResponse.createByErrorCodeMessage(resultCodeEnum.getCode(),resultCodeEnum.getDisplay());
    }

    /**
     * 操作失败
     *
     * @param msg 错误信息
     * @param <T> 返回对象类型
     * @return Result
     */
    public <T extends Serializable> ServerResponse<T> doError(ResultCodeEnum resultCodeEnum, String msg) {
        return ServerResponse.createByErrorCodeMessage(resultCodeEnum, msg);
    }
    /**
     * 操作成功
     *
     * @param <T> 操作类型
     * @return Result
     */
    public <T extends Serializable> ServerResponse<T> doSuccess(T data) {
        return ServerResponse.createBySuccess(data);
    }

    /**
     * 操作失败
     *
     * @param e   错误信息
     * @param <T> 返回对象类型
     * @return Result
     */
    public <T extends Serializable> ServerResponse<T> doError(Exception e) {
        return this.doError(e, e.getLocalizedMessage());
    }

    /**
     * 操作失败
     *
     * @param e   错误信息
     * @param msg 错误信息
     * @param <T> 返回对象类型
     * @return Result
     */
    public <T extends Serializable> ServerResponse<T> doError(Exception e, String msg) {
        ResultCodeEnum resultCodeEnum = ResultCodeEnum.CODE9999;
        if (e instanceof BusinessException) {
            resultCodeEnum = ((BusinessException) e).getResultCodeEnum();
        }
        return ServerResponse.createByErrorCodeMessage(resultCodeEnum, msg);
    }

}
